import * as userUtil from '../controllerImplement/user.js'
import * as test_tableUtil from '../controllerImplement/test_table.js'     
import {connection} from './mysql.mjs' 
import  querystring from 'querystring'
const routerOptions = [{url:'/user/',implement:userUtil},{url:'/test_table/',implement:test_tableUtil}]
const controlApi = (req, res)=>{
      if(req.url == "/getTables"){
        getTables(req, res)
      }
      else if(req.url == "/getTableColumns"){
        getTableColumns(req, res)
      }
      else{
        const util = getUtil(req.url)
        if(util){
          util.control(req,res)
        }
      }

      function getUtil  (url){
        let res = null
        routerOptions.forEach((item)=>{
            if(url.startsWith(item.url)){
                res = item.implement
            }
        })
        return res
      }
      /**获取所有表 */
      function getTables(req, res){
        const selectQuery = 'show tables';
        connection.query(selectQuery, (err, results) => {
            if (err) {
              console.error('Error querying data:', err);
              res.writeHead(200, { 'Content-Type': 'application/json' });
              res.end(JSON.stringify('Error querying data'));
            }
            else{
              res.writeHead(200, { 'Content-Type': 'application/json' });
              res.end(JSON.stringify(results));
            }
          });
      }
      /**获取表的所有字段和属性 */
      function getTableColumns(req, res){
        let parsedBody = null;
        if (req.method === 'POST') {
            let body = '';
            req.on('data', (chunk) => {
                body += chunk.toString();
            });
            
            req.on('end', () => {
                parsedBody = querystring.parse(body);
                const {tableName} = parsedBody;

                const selectQuery = 'DESCRIBE '+tableName;
                connection.query(selectQuery, (err, results) => {
                    if (err) {
                      console.error('Error querying data:', err);
                      res.writeHead(200, { 'Content-Type': 'application/json' });
                      res.end(JSON.stringify('Error querying data'));
                    }
                    else{
                      res.writeHead(200, { 'Content-Type': 'application/json' });
                      res.end(JSON.stringify(results));
                    }
                  });
            });
        }

      }
}
export  {controlApi};